package TestConcurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-17
 * Time: 10:25
 */
public class DemoCallable {
    public static void main(String[] args) {
        //通过callable描述一个任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i <=1000 ; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        //需要创建线程来计算
        //在创建线程之前只要一个辅助类
        FutureTask<Integer> task = new FutureTask<>(callable);
        Thread t = new Thread(task);
        t.start();

        //凭借标记得到任务结果,如果线程任务没有执行结束,get就会阻塞,直到任务结束
        try {
            System.out.println(task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
